package cn.dugcrs.basic.utils;

import cn.dugcrs.basic.jwt.JwtUtils;
import cn.dugcrs.basic.jwt.LoginSuccseeObj;
import cn.dugcrs.basic.jwt.Payload;
import cn.dugcrs.basic.jwt.RsaUtils;
import cn.dugcrs.user.domain.Logininfo;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;

import static cn.dugcrs.basic.jwt.JwtUtils.getInfoFromToken;

/**
 * 获取上下文
 * 1.获取当前登录用户
 * 2.获取当前登录用户的
 *
 */
public class LoginContext {

    public static Logininfo getCurrentLogininfo(HttpServletRequest request){
        // 从请求头中获取token，不能为空
        String utoken = request.getHeader("token");
        // 空校验
        if (StringUtils.isEmpty(utoken)) {
            return null;
        }
        try {
            // 解密jwt字符串
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<LoginSuccseeObj> payload = getInfoFromToken(utoken, publicKey, LoginSuccseeObj.class);
            LoginSuccseeObj loginSuccseeObj = (LoginSuccseeObj)payload.getUserInfo();
            return loginSuccseeObj.getLogininfo();
        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }

    }

}
